package servlets.adsServlets;

import java.io.IOException;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import managers.JsonManager;

import org.jsoup.Jsoup;

import structures.AD;

public class ShowADServlet extends HttpServlet {

	private static final long serialVersionUID = 836278561331331989L;
	private static final String URLBASE = "http://localhost:8080/ISellToYouRESTWebService/GetAD";
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String answer, idAdvertisement, wikiInfo;
		
		URL url;
		JsonManager jsonManager;
		AD advertisement = null;
		jsonManager = new JsonManager();
		idAdvertisement = request.getParameter("idAdvertisement");
		wikiInfo = request.getParameter("WikiInfo");
		
		try {
			url = new URL(URLBASE + "?idAdvertisement=" + idAdvertisement + "&WikiInfo=" + wikiInfo);
			answer = Jsoup.connect(url.toString()).ignoreContentType(true).execute().body();
			
			if(answer.equals("null"))
				throw new Exception();
			
			advertisement = jsonManager.toAD(answer);
			
			request.getSession().setAttribute("advertisement", advertisement);
			try {
				response.sendRedirect(request.getContextPath() + "/advertisement.jsp");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (Exception e1) {
			e1.printStackTrace();
			try {
				response.sendRedirect(request.getContextPath() + "/advertisement.jsp");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
